package com.firexxx.study;

import com.firexxx.study.transformers.CustomVisitorTransformer;

import java.io.File;
import java.lang.instrument.Instrumentation;

/**
 * @description: TODO
 * @throws:
 * @author: zhuangzhang2
 * @date: 2020/07/02 12:27
 */
public class CustomJavaAgent {

    private static ClassLoader arthasClassLoader;

//    public static void agentmain(String args, Instrumentation inst) {
//        System.out.println("=========premain方法执行========");
//        //System.out.println(agentOps);
//        // 添加Transformer
//        inst.addTransformer(new CustomClassFileTransformer(), true);
//    }

    public static boolean delete(String path){
        File file = new File(path);

        if(!file.exists()){
            return false;
        }

        if(file.isFile()){
            return file.delete();
        }

        File[] files = file.listFiles();
        for (File f : files) {
            if(f.isFile()){
                if(!f.delete()){
                    System.out.println(f.getAbsolutePath()+" delete error!");
                    return false;
                }
            } else {
                if(!delete(f.getAbsolutePath())){
                    return false;
                }
            }
        }

        return file.delete();
    }

    public static void premain(String agentOps, Instrumentation inst) {
        System.out.println("=========premain方法执行========");
        System.out.println(agentOps);

        String prefix = null;
        boolean detailSwitch = false;
        try {
            String[] items = agentOps.split("&");
            for (String item : items) {
                String[] parts = item.split("=");
                if (parts[0].equals("prefix")) {
                    prefix = parts[1];
                } else if (parts[0].equals("detail")) {
                    detailSwitch = Boolean.parseBoolean(parts[1]);
                }
            }
        } catch (Throwable t) {
//            t.printStackTrace();
        }

        // 添加Transformer
//        inst.addTransformer(new CustomClassFileTransformer(agentOps));

        try {
            delete("output/classes/");
            System.out.println("删除目录output/classes/成功");
        } catch (Throwable t) {
            t.printStackTrace();
        }

        inst.addTransformer(new CustomVisitorTransformer(prefix, detailSwitch));
    }

    private static ClassLoader getClassLoader(Instrumentation inst) throws Throwable {
        // 构造自定义的类加载器，尽量减少Arthas对现有工程的侵蚀
        return loadOrDefineClassLoader();
    }

    private static ClassLoader loadOrDefineClassLoader() throws Throwable {
        if (arthasClassLoader == null) {
            arthasClassLoader = new CustomClassloader(null);
        }
        return arthasClassLoader;
    }
}